#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
验证过程中使用 InstrumentController 的示例
演示如何在验证引擎中复用校准过程的仪表操作逻辑
"""

import time
from PyQt5.QtCore import QObject, pyqtSignal
from instrument_controller import InstrumentController


class VerificationProcess(QObject):
    """验证过程示例类
    
    展示如何使用 InstrumentController 进行验证测量
    """
    
    log_signal = pyqtSignal(str)
    
    def __init__(self, parent=None):
        super().__init__(parent)
        
        # 创建仪表控制器实例
        self.instrument_controller = InstrumentController(self)
        
        # 连接日志信号
        self.instrument_controller.log_signal.connect(self.log_signal.emit)
        
        # 仪器实例和控件引用
        self.sg_widget = None
        self.sa_widget = None
        self.attenuator = None
        
        # 验证配置
        self.sg_power = 0.0  # 信号源输出功率 (dBm)
        self.loss_reader = None  # 线损数据读取器
    
    def initialize_for_verification(self, sg_widget, sa_widget, attenuator, loss_reader=None):
        """初始化验证测量环境
        
        Args:
            sg_widget: 信号源控件
            sa_widget: 频谱仪控件
            attenuator: 数字衰减器实例
            loss_reader: 线损数据读取器（可选）
        
        Returns:
            bool: 初始化是否成功
        """
        self.sg_widget = sg_widget
        self.sa_widget = sa_widget
        self.attenuator = attenuator
        self.loss_reader = loss_reader
        
        # 初始化仪器
        if not self.instrument_controller.initialize_instruments(sg_widget, sa_widget, attenuator):
            return False
        
        # 设置验证模式参数
        try:
            self.instrument_controller.setup_verification_mode(self.sg_power)
            self.log_signal.emit("验证环境初始化完成")
            return True
        except Exception as e:
            self.log_signal.emit(f"验证环境初始化失败: {str(e)}")
            return False
    
    def perform_verification_test(self, frequency, target_attenuation, theoretical_compensation):
        """执行单个验证测试
        
        Args:
            frequency: 测试频率 (MHz)
            target_attenuation: 目标衰减值 (dB)
            theoretical_compensation: 理论补偿值 (dB)
        
        Returns:
            dict: 测试结果字典
        """
        try:
            self.log_signal.emit(f"开始验证测试: {frequency} MHz, 目标衰减 {target_attenuation} dB")
            
            # 使用仪表控制器执行验证测量
            measured_power = self.instrument_controller.perform_verification_measurement(
                frequency, theoretical_compensation)
            
            if measured_power is None:
                return {
                    'frequency': frequency,
                    'target_attenuation': target_attenuation,
                    'theoretical_compensation': theoretical_compensation,
                    'measured_power': 0.0,
                    'actual_attenuation': 0.0,
                    'error': 0.0,
                    'status': '失败'
                }
            
            # 应用线损补偿
            loss_compensation = 0.0
            if self.loss_reader:
                loss_compensation = self.loss_reader.get_loss_at_frequency(frequency)
            
            compensated_power = measured_power - loss_compensation
            
            # 计算实际衰减 = 信号源功率 - 补偿后测量值
            actual_attenuation = self.sg_power - compensated_power
            
            # 计算误差
            error = actual_attenuation - target_attenuation
            
            result = {
                'frequency': frequency,
                'target_attenuation': target_attenuation,
                'theoretical_compensation': round(theoretical_compensation, 2),
                'measured_power': round(measured_power, 2),
                'compensated_power': round(compensated_power, 2),
                'actual_attenuation': round(actual_attenuation, 2),
                'error': round(error, 2),
                'status': '完成'
            }
            
            self.log_signal.emit(
                f"验证结果: 实际衰减={actual_attenuation:.2f}dB, "
                f"误差={error:.2f}dB"
            )
            
            return result
            
        except Exception as e:
            self.log_signal.emit(f"验证测试失败: {str(e)}")
            return {
                'frequency': frequency,
                'target_attenuation': target_attenuation,
                'theoretical_compensation': theoretical_compensation,
                'measured_power': 0.0,
                'actual_attenuation': 0.0,
                'error': 0.0,
                'status': '失败'
            }
    
    def perform_batch_verification(self, test_list):
        """执行批量验证测试
        
        Args:
            test_list: 测试列表，每个元素包含 frequency, target_attenuation, theoretical_compensation
        
        Returns:
            list: 测试结果列表
        """
        results = []
        
        for i, test_item in enumerate(test_list):
            self.log_signal.emit(f"执行测试 {i+1}/{len(test_list)}")
            
            result = self.perform_verification_test(
                test_item['frequency'],
                test_item['target_attenuation'],
                test_item['theoretical_compensation']
            )
            
            results.append(result)
            
            # 短暂延迟
            time.sleep(0.1)
        
        # 统计结果
        successful_tests = sum(1 for r in results if r['status'] == '完成')
        failed_tests = len(results) - successful_tests
        
        self.log_signal.emit(f"批量验证完成: 成功 {successful_tests}, 失败 {failed_tests}")
        
        return results
    
    def shutdown(self):
        """关闭验证过程并清理资源"""
        if self.instrument_controller:
            self.instrument_controller.shutdown_instruments()
            self.log_signal.emit("验证过程已关闭")


# 使用示例
def example_usage():
    """使用示例"""
    from PyQt5.QtWidgets import QApplication
    import sys
    
    app = QApplication(sys.argv)
    
    # 创建验证过程实例
    verification = VerificationProcess()
    
    # 连接日志信号到控制台输出
    verification.log_signal.connect(print)
    
    # 假设已经有了sg_widget, sa_widget, attenuator实例
    # verification.initialize_for_verification(sg_widget, sa_widget, attenuator)
    
    # 定义测试列表
    test_list = [
        {'frequency': 100, 'target_attenuation': 10.0, 'theoretical_compensation': 9.8},
        {'frequency': 500, 'target_attenuation': 20.0, 'theoretical_compensation': 19.7},
        {'frequency': 1000, 'target_attenuation': 30.0, 'theoretical_compensation': 29.9},
    ]
    
    # 执行批量验证（需要先初始化）
    # results = verification.perform_batch_verification(test_list)
    
    # 关闭
    # verification.shutdown()
    
    print("验证过程示例代码已准备完毕")


if __name__ == "__main__":
    example_usage()